<?php

class Core_Api_Attachment{
	
	/**
	 * @return array {object_type=>array{object_id,},}
	 */
	function groupAttachments($resource, $limit = 5)
	{

		$table = Nuo::getTable('core/attachment');

		$select = $table -> select();
		$select -> where('resource_id=?', $resource -> getItemId());
		$select -> limit($limit);
		$rows = $table -> fetchAll($select);
		$groups = array();

		foreach ($rows as $row)
		{
			list($type, $id) = explode('_', $row['object_id']);
			$groups[$type][] = $id;
		}

		return $groups;
	}

	function getAttachments($resource, $limit = 5)
	{
		$table = Nuo::getTable('core/attachment');

		$select = $table -> select();

		$select -> where('resource_id=?', $resource -> getItemId());

		$select -> limit($limit);

		return $table -> fetchAll($select);
	}

	/**
	 * @param Database_Model_Item $resource
	 * @param Database_Model_Item $object
	 * @return Database_Model_Item
	 */
	function addAttachment($resource, $object)
	{
		$table = Nuo::getTable('core/attachment');

		$new = $table -> fetchNew();

		$new -> resource_id = $resource -> getItemId();
		$new -> object_id = $object -> getItemId();

		$new -> save();

		if (isset($resource -> attachment_count))
		{
			$resource -> attachment_count = $resource -> attachment_count + 1;
			$resource -> save();
		}

		return $resource;
	}

	/**
	 * @param Database_Model_Item $resource
	 * @param array  $objects
	 */
	function addAttachments($resource, $objects)
	{
		$table = Nuo::getTable('core/attachment');
		$counter = 0;

		foreach ($objects as $object)
		{
			$new = $table -> fetchNew();

			$new -> resource_id = $resource -> getItemId();

			if (!is_object($object))
			{
				continue;
			}

			$new -> object_id = $object -> getItemId();

			$new -> save();

			++$counter;
		}
		if (isset($resource -> attachment_count))
		{
			$resource -> attachment_count = $resource -> attachment_count + $counter;
			$resource -> save();
		}
		return $resource;
	}
}
